<template>
  <div>
    <van-nav-bar
      title="注册"
      left-text="返回"
      left-arrow
      @click-left="backHandle"
    />
    <van-form @submit="onSubmit">
      <van-field
        v-model="user.username"
        name="username"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="user.password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-field
        v-model="user.telephone"
        name="telephone"
        label="电话"
        placeholder="电话"
        :rules="[{ pattern, message: '请填写电话' }]"
      />
      <van-field name="gender" label="性别">
        <template #input>
          <van-radio-group v-model="user.gender" direction="horizontal">
            <van-radio name="male">男</van-radio>
            <van-radio name="female">女</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field name="uploader" label="上传头像">
        <template #input>
          <van-uploader v-model="user.uploader" />
        </template>
      </van-field>
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">
          注册
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import axios from "axios";
import qs from "../../../node_modules/qs";
export default {
  data() {
    return {
      user: {
        username: "",
        password: "",
        telephone: "",

        gender: "",
        uploader: [{ url: "https://img.yzcdn.cn/vant/leaf.jpg" }],
      },
      pattern: /\d{11}/,
    };
  },
  methods: {
    backHandle() {
      this.$router.go(-1);
    },
    onSubmit(values) {
      console.log("submit", values);
      axios
        .get("http://localhost:8888/register?" + qs.stringify(values))
        .then((res) => {
          console.log(res.data);
          localStorage.setItem("username", values.username);
          if (res.data.status == 200) {
            this.$router.go(-1);
          } else if (res.data.status == 300) {
            alert("用户已存在，请重新输入");
            this.user = {};
          }
        });
    },
  },
};
</script>

<style></style>
